package com.ssyc.common.quanzi;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.utils.TextUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.ssyc.common.R;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.BaseApplication;
import com.ssyc.common.base.Constants;
import com.ssyc.common.bean.BusInfo;
import com.ssyc.common.glide.ImageUtil;
import com.ssyc.common.http.HttpAdress;
import com.ssyc.common.http.HttpUtils;
import com.ssyc.common.manager.AccountUtils;
import com.ssyc.common.manager.BqaManager;
import com.ssyc.common.manager.OnloadingMoreListener;
import com.ssyc.common.manager.SrfManager;
import com.ssyc.common.manager.StateBarManager;
import com.ssyc.common.utils.GsonUtil;
import com.ssyc.common.utils.UiUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 个人的朋友圈
 * Created by Administrator on 2018/7/10 0010.
 */

public class PersonCircleActivity extends BaseActivity implements View.OnClickListener, SrfManager.OnPullRefreshListener, OnloadingMoreListener {

    private RecyclerView rv;
    private SmartRefreshLayout srl;
    private RelativeLayout rlContent;
    private RelativeLayout rlLoading;
    private RelativeLayout rlBack;

    //数据集合
    private List<QuanZiInfo.CirclelistBean> oldDatas;

    //头布局
    private View headView;

    //空视图
    private View emptyView;

    //适配器
    private CircleRvAdapter adapter;

    //分页
    private int page = 0;

    //头布局的头像
    private ImageView ivHead;

    //头布局的背景
    private ImageView ivTop;

    //头布局的名称
    private TextView tvName;


    private String acc2;

    private String role2;

    private String name;

    private String icon;

    //更新页面的标识
    public static final int UPDATE = 0x550;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.base_activity_person_circle;
    }

    @Override
    protected void init() {

        showContent();

        //配置状态栏颜色
        initStateColor();

        initIntent();

        //初始化视图
        initView();

        //初始化下拉刷新
        initSrf();

        //设置列表
        initRv();

        //请求服务器
        http(BqaManager.NORML);

    }

    /**
     * 接受传值
     */
    private void initIntent() {

        acc2 = getIntent().getStringExtra("acc2");
        role2 = getIntent().getStringExtra("role2");

        name = getIntent().getStringExtra("name");
        icon = getIntent().getStringExtra("icon");
    }


    /**
     * 配置状态栏颜色的方法
     */
    private void initStateColor() {
        //设置6.0以后沉浸状体栏的问题
        StateBarManager.setBarWithUltimateBar(this, getResources().getColor(com.ssyc.common.R.color.titlebg),
                getResources().getColor(com.ssyc.common.R.color.nav_color));
    }


    /**
     * 初始化视图
     */
    public void initView() {
        rlBack = findViewById(R.id.rlback);
        rlBack.setOnClickListener(this);
        rv = findViewById(R.id.rv);
        srl = findViewById(R.id.srl);
        rlContent = findViewById(R.id.rl_content);
        rlLoading = findViewById(R.id.rl_loading);
        rlLoading.setVisibility(View.VISIBLE);
    }


    /**
     * 初始化下拉刷新控件
     */
    private void initSrf() {
        //配置下拉刷新控件
        SrfManager.setSmartByPullListener(srl, this);
    }

    /**
     * 初始化列表控件
     */
    private void initRv() {
        oldDatas = new ArrayList<>();
        headView = View.inflate(this, R.layout.base_rv_head_myquanzi, null);
        ivHead = headView.findViewById(R.id.ivhead);
        ivHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //头像点击事件跳转到个人详情资料界面
                UiUtils.startActivity(PersonCircleActivity.this, PersonInfoActivity.class);
            }
        });
        ivTop = headView.findViewById(R.id.lv_top);
        tvName = headView.findViewById(R.id.tv_name);
        emptyView = View.inflate(this, R.layout.base_rv_common_empty_view_white_bg, null);
        adapter = new CircleRvAdapter(this, R.layout.base_item_rv_picture, oldDatas);
        adapter.addHeaderView(headView);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //条目的点击事件,进入到详情界面
                Intent intent = new Intent(PersonCircleActivity.this, PersonCircleDetailActivity.class);
                intent.putExtra("data", oldDatas.get(position));
                startActivity(intent);
            }
        });

        //设置头布局的相关内容
        ImageUtil.displayImage(BaseApplication.context, ivHead, icon, R.drawable.base_default_head);
        //姓名
        tvName.setText(name);
    }


    /**
     * 请求服务器的方法
     *
     * @param method
     */
    private void http(final int method) {
        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            page = 0;
        } else {
            page++;
        }
        Map<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("acc", acc2);
        map.put("acc2", AccountUtils.getAccount(this));
        map.put("role", role2);
        map.put("role2", AccountUtils.getRole(this));
        map.put("friendlist", "");
        map.put("page", page + "");
        map.put("platform", "8");
        if (method == BqaManager.NORML || method == BqaManager.PULLREFRESH) {
            //第一次请求时,传入时间为0
            map.put("update_time", "0");
        } else {
            //加载更多时传入当前数据源的最后一个数据的update_time
            map.put("update_time", oldDatas.get(oldDatas.size() - 1).getUpdate_time());
        }

        HttpUtils.post(HttpAdress.MYCIRCLE, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                BqaManager.setErrorNet(rlLoading, srl, method, adapter);
            }

            @Override
            public void onResponse(String response, int id) {
                if (rlLoading != null && rlLoading.getVisibility() == View.VISIBLE) {
                    rlLoading.setVisibility(View.GONE);
                }

                if (rlContent != null && rlContent.getVisibility() != View.VISIBLE) {
                    rlContent.setVisibility(View.VISIBLE);
                }

                if (!TextUtils.isEmpty(response)) {
                    QuanZiInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, QuanZiInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    Log.i("test", response);
                    if (null != info) {
                        if ("200".equals(info.getState())) {
                            //返回成功
                            if (method == BqaManager.NORML) {

                                //设置头布局的背景
                                ImageUtil.displayImage(BaseApplication.context, ivTop, info.getCircle_bgimg(), R.drawable.base_common_timg);
                            }

                            //更新列表
                            List<QuanZiInfo.CirclelistBean> newDatas = info.getCirclelist();

                            if (newDatas != null) {
                                if (method == BqaManager.NORML) {
                                    oldDatas.clear();
                                    oldDatas.addAll(newDatas);
                                    BqaManager.setRv(emptyView, PersonCircleActivity.this, adapter, rv, PersonCircleActivity.this);
                                    adapter.setEnableLoadMore(true);
                                } else {
                                    //更新数据
                                    BqaManager.updateRvBySmf(method, srl, rv, oldDatas, newDatas, adapter);
                                }
                            }
                        } else if ("101106".equals(info.getState())) {
                            //没有圈子数据
                            if (method == BqaManager.LOADINDGMORE) {
                                adapter.loadMoreEnd();
                            } else if (method == BqaManager.PULLREFRESH) {
                                srl.finishRefresh();
                            }else {
                                oldDatas.clear();
                                BqaManager.setRv(null, PersonCircleActivity.this, adapter, rv, PersonCircleActivity.this);
                                adapter.setEnableLoadMore(true);
                            }
                        } else {
                            UiUtils.Toast(Constants.ERRORSTATE + info.getState(), false);
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });
    }


    /**
     * 下拉刷新
     *
     * @param refreshlayout
     */
    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        http(BqaManager.PULLREFRESH);
    }

    /**
     * 加载更多
     */
    @Override
    public void onLoadMore() {
        http(BqaManager.LOADINDGMORE);
    }

    /**
     * 点击事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.rlback) {
            //返回
            finish();
        }

    }

    /**
     * 事件处理
     *
     * @param busInfo
     */
    @Override
    public void busEvent(BusInfo busInfo) {
        super.busEvent(busInfo);
        if (null != busInfo && busInfo.getType() == UPDATE) {
            Log.i("test", "收到更新消息了");
            http(BqaManager.PULLREFRESH);
        }
    }
}
